package apis

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"net/http"
	"strings"
	"tuowei.com/app/api/models"
	"tuowei.com/app/api/service"
	"tuowei.com/app/api/service/dto"
	"tuowei.com/pkg/xlog"
)

type SysRegion struct {
	api.Api
}

func (e SysRegion) GetProvinceByCity(c *gin.Context) {
	s := service.SysRegion{}
	req := dto.GetProvinceByCityReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Default(c.Request.Method, c.ContentType())).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	city := strings.Trim(req.CityName, "市")
	xlog.Error(city)
	city = strings.Trim(city, "盟")
	xlog.Error(city)
	obj := new(models.SysRegion)
	err = e.Orm.Table(obj.TableName()).Where("level = 2").Where("name = ?", city).First(obj).Error
	if err != nil {
		e.Error(http.StatusInternalServerError, err, "无法定位到当前城市")
		return
	}
	provinceObj := new(models.SysRegion)
	err = e.Orm.Table(provinceObj.TableName()).Where("level = 1").Where("id = ?", obj.ParentId).First(provinceObj).Error
	if err != nil {
		e.Error(http.StatusInternalServerError, err, "当前城市无上级")
	}
	e.OK(provinceObj, "success")
}

func (e SysRegion) GetTree(c *gin.Context) {
	s := service.SysRegion{}
	req := dto.SysRegionReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Form, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	list := make([]models.SysRegionList, 0)
	err = s.GetList(&req, &list)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}

	e.OK(list, "查询成功")
}
